package com.zhiyou.aifeng.smart_machine

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.jeremyliao.liveeventbus.utils.observe
import com.zhiyou.aifeng.common.base.getColorEx
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common.helper.toNotInt
import com.zhiyou.aifeng.common_ui.base.*
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.oss.scaleImage
import com.zhiyou.aifeng.common_ui.utils.*
import com.zhiyou.aifeng.model.MachineData
import com.zhiyou.aifeng.utils.addOnScrollChanged
import com.zhiyou.aifeng.utils.setEmptyIcon
import com.zhiyou.aifeng.viewmodel.MachineViewModel
import kotlinx.android.synthetic.main.activity_machine.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class MachineActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_machine)
        initTitle(title = "我的农机", divider = false)

        swipe_refresh.isRefreshing = true
        getData()
    }

    override fun getViewModel() = get<MachineViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        initList()

        observe("machineList") {
            val items = it.split(",")
            when (items[0]) {
                "add" -> updateList()
                "delete" -> {
                    val position = items[1].toNotInt()
                    if (position > -1) {
                        mList.removeAt(position)
                        mAdapter.notifyItemRemoved(position)
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                        machine_bottom.bottomShow()
                    } else updateList()
                }
                "update" -> {
                    val position = items[1].toNotInt()
                    if (position > -1) {
                        val item = mList[position] as MachineData
                        item.tool_status = !item.tool_status
                        mAdapter.notifyItemChanged(position)
                    } else updateList()
                }
            }
        }

        bt_add01.oneClick {
            if (getString("auth") != "2") {
                toast("您还未通过实名认证，暂无法操作！")
                return@oneClick
            }

            startActivity<MachineAddActivity>("type" to 0)
        }

        bt_add02.oneClick {
            if (getString("auth") != "2") {
                toast("您还未通过实名认证，暂无法操作！")
                return@oneClick
            }

            startActivity<MachineAddActivity>("type" to 1)
        }
    }

    private fun initList() {
        empty_img.setEmptyIcon()
        empty_hint.text = "暂无相关农机信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            loadLinear(baseContext, swipe_refresh)

            mAdapter = SlimAdapter.create()
                .register<MachineData>(R.layout.item_machine_list) { data, injector ->

                    val index = mList.indexOf(data)
                    val isLast = index == mList.size - 1

                    injector.text(
                        R.id.item_machine_name,
                        "${data.brand_name + data.vehicle_type_name}/${data.model_name}"
                    )
                        .text(R.id.item_machine_suit, "适合作业：${data.work_name}")
                        .text(
                            R.id.item_machine_check,
                            when (data.check_status) {
                                "0" -> "审核中"
                                "2" -> "未通过"
                                else -> ""
                            }
                        )
                        .text(
                            R.id.item_machine_status,
                            when (data.check_status) {
                                "0" -> "正常"
                                "2" -> "正常"
                                else -> {
                                    if (data.tool_status) "正常"
                                    else "不可用"
                                }
                            }
                        )
                        .textColor(
                            R.id.item_machine_status,
                            when (data.check_status) {
                                "0" -> getColorEx(R.color.colorAccent)
                                "2" -> getColorEx(R.color.colorAccent)
                                else -> getColorEx(if (data.tool_status) R.color.colorAccent else R.color.gray)
                            }
                        )
                        .with<ImageView>(R.id.item_machine_img) {
                            it.loadImage(data.img.scaleImage())
                        }
                        .with<ImageView>(R.id.item_machine_switch) {
                            it.setImageResource(
                                if (data.tool_status) R.mipmap.icon_open
                                else R.mipmap.icon_close
                            )
                        }
                        .visibility(
                            R.id.item_machine_switch,
                            if (data.check_status == "1") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_machine_divider1,
                            if (isLast) View.GONE else View.VISIBLE
                        )
                        .visibility(
                            R.id.item_machine_divider2,
                            if (isLast) View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_machine_switch) {
                            changeStatus(data.id, !data.tool_status, index)
                        }
                        .clicked(R.id.item_machine) {
                            when (data.check_status) {
                                "2" -> {
                                    startActivity<MachineAddActivity>(
                                        "id" to data.id,
                                        "type" to data.type.toNotInt(),
                                        "mode" to "modify"
                                    )
                                }
                                else -> {
                                    startActivity<MachineDetailActivity>(
                                        "id" to data.id,
                                        "index" to index
                                    )
                                }
                            }
                        }
                        .longClicked(R.id.item_machine) {
                            deleteItem(data.id, index, data.type.toNotInt())
                            true
                        }
                }
                .attachTo(this)

            addOnScrollChanged(
                onShow = { machine_bottom.bottomShow() },
                onHide = { machine_bottom.bottomHide(85f) }
            )
        }
    }

    private fun changeStatus(brandId: String, status: Boolean, index: Int) {
        getViewModel().request(
            requestUrl = BaseUrl.status,
            params = *arrayOf(
                "id" to brandId,
                "toolStatus" to status
            ),
            onResult = {
                toast("修改状态成功！")
                (mList[index] as MachineData).tool_status = status
                mAdapter.notifyItemChanged(index)
            }
        )
    }

    private fun deleteItem(brandId: String, index: Int, type: Int) {
        showHintDialog(
            title = "删除农${if (type == 1) "具" else "机"}",
            hint = "确定要删除农${if (type == 1) "具" else "机"}吗？"
        ) {
            getViewModel().request(
                requestUrl = BaseUrl.delBrand,
                params = *arrayOf("id" to brandId),
                onResult = {
                    toast("删除成功！")
                    mList.removeAt(index)
                    mAdapter.notifyItemRemoved(index)
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    machine_bottom.bottomShow()
                }
            )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getMachineList(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.updateData(mList)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true
        machine_bottom.bottomShow()

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

}